//
//  XLComposeView.swift
//  SinaWeibo
//
//  Created by 李凯 on 16/9/9.
//  Copyright © 2016年 kevin. All rights reserved.
//

import UIKit
import pop

class XLComposeView: UIView {
    //初始化一个数组, 用来保存按钮
    var buttons: [UIButton] = [UIButton]()
    //外界传入的控制器
    var target: UIViewController?
    //用来保存字典数组
    var infoArray: NSArray?

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        //let image = getScreenSnap()?.applyLightEffect()
        //let data = UIImagePNGRepresentation(image!)! as NSData
        //data.write(toFile: "/Users/likai/Desktop/bug.png", atomically: true)
        //backgroundColor = UIColor.red
        frame.size = UIScreen.main.bounds.size
        
        addSubview(bgImage)
        addSubview(sloganImg)
        //布局
        bgImage.snp_makeConstraints { (make) in
            make.edges.equalTo(self)
        }
        sloganImg.snp_makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.top.equalTo(100)
        }
        addBtns()

    }
    
    //添加按钮
    func addBtns() {
        
        // 按钮的宽度
        let itemW: CGFloat = 80
        let itemH: CGFloat = 110
        // 求出每按钮之间的间距
        let itemMargin = (HMScreenW - 3 * itemW) / 4
        
        // 读取 compose.list
        let path = Bundle.main.path(forResource: "compose.plist", ofType: nil)!
        let array = NSArray(contentsOfFile: path)!
        
        //记录数组信息
        self.infoArray = array
        
        for i in 0..<array.count {
            let button = XLComposeBtn(textColor: UIColor.darkGray, fontSize: 14)
            //添加点击事假
            button.addTarget(self, action: #selector(buttonClick(button:)), for: UIControlEvents.touchUpInside)
            
            // 取出对应位置的字典
            let dict = array[i] as! [String: String]
            // 设置图标与文字
            button.setImage(UIImage(named: dict["icon"]!), for: UIControlState.normal)
            button.setTitle(dict["title"]!, for: UIControlState.normal)
            // 设置大小
            button.frame.size = CGSize(width: itemW, height: itemH)
            
            // 1. 求出按钮在第几列
            let col = i % 3
            // 2. 求出按钮在第几行
            let row = i / 3
            
            // 通过列数求出x值
            let x = CGFloat(col) * itemW + CGFloat(col + 1) * itemMargin
            // 通过行数求出y值
            let y = CGFloat(row) * itemH + HMScreenH
            // 设置按钮的位置
            button.frame.origin = CGPoint(x: x, y: y)
            
            addSubview(button)
            //将按钮保存到数组
            buttons.append(button)
        }

    }
    
    //按钮点击事件
    func buttonClick(button: UIButton) {
        UIView.animate(withDuration: 1, animations: { 
            for value in self.buttons {
                //如果点击按钮与遍历到的按钮是同一个按钮, 就放大
                if button == value {
                    value.transform = CGAffineTransform(scaleX: 2, y: 2)
                }else{
                    //否则就缩小
                    value.transform = CGAffineTransform(scaleX: 0.2, y: 0.2)
                }
                value.alpha = 0.1
            }
            }) { (_) in
                //动画执行完成之后执行
                //弹出控制器
                //从按钮数组中取到按钮所在的index
                let index = self.buttons.index(of: button) ?? 0
                //通过index取到plist数组中对应的字典
                let dict = self.infoArray![index] as! [String: String] //强转成string类型的字典
                if let name = dict["class"] {
                    //let string = NSStringFromClass(XLComposeViewController.classForCoder())
                    //print(string)
                    //通过类名, 初始化类
                    let type = NSClassFromString(name)! as! UIViewController.Type
                    let vc = type.init()
                    self.target?.present(XLNavigationController(rootViewController: vc), animated: true, completion: {
                        self.removeFromSuperview()
                    })
                }
                
        }
        
    }
    
    //外界传一个控制器进来
    func show(target: UIViewController) {
       // let window = UIApplication.shared.keyWindow
        //window?.addSubview(self)
        
        //记录外界传入的控制器 tabbarController
        self.target = target
        
        self.target?.view.addSubview(self)
        
        //遍历数组按钮
        for(index, button) in buttons.enumerated() {
            anim(button: button, index: index, isUp: true)
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for(index, button) in buttons.reversed().enumerated(){
            anim(button: button, index: index, isUp: false)
        }
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.5) {
            self.removeFromSuperview()
        }
    }
    
    func anim(button: UIButton, index: Int, isUp: Bool) {
        let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        anim?.toValue = NSValue.init(cgPoint: CGPoint(x: button.center.x, y: button.center.y+(isUp ? -350 : 350)))
        anim?.springBounciness = 12
        anim?.springSpeed = 10
        //让每个按钮延迟一定时间再执行动画
        anim?.beginTime = CACurrentMediaTime() + Double(index) * 0.025
        button.pop_add(anim, forKey: nil)
    }
    
    
    
    func getScreenSnap() -> UIImage? {
        // 先获取到window
        let window = UIApplication.shared.keyWindow!
        // 开启上下文
        // 如果最后一参数传入0的话，会按照屏幕的真实大小来截取，就是不会截取缩放之后的内容
        UIGraphicsBeginImageContextWithOptions(window.bounds.size, false, 0)
        // 将window的内容渲染到上下文中
        window.drawHierarchy(in: window.bounds, afterScreenUpdates: false)
        // 取到上下文中的图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        // 关闭上下文
        UIGraphicsEndImageContext()
        // 将图片保存到桌面
        //let data = UIImagePNGRepresentation(image!)! as NSData
        //data.write(toFile: "/Users/likai/Desktop/bug.png", atomically: true)
        // 返回结果
        return image
    }
    
    //懒加载
    lazy var bgImage: UIImageView = {
        let imageView = UIImageView(image: self.getScreenSnap()?.applyLightEffect())
        return imageView
    }()
    
    lazy var sloganImg: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "compose_slogan"))
        return imageView
    }()

}
